<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\Db;
use think\exception\HttpResponseException;
use think\Response;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach ($iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        ) as $item) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}

/**
 * 发送验证码方法
 * @param int $templateId 短信模板Id
 * @param string $codeVal 验证码
 * @param string $cellPhone 手机号码
 * @return string 返回信息
 */
function sendSms(int $templateId = 0, string $codeVal = "", string $cellPhone = "")
{
    $requestUrl = "http://mpt.nmgfdkj.com/Home/Nsms/v1";
    $tName = 'sms_logs';
    if (empty($templateId) || empty($codeVal)) {
        return '数据异常';
    }
    $Regular = '/^((\+86-)|(86-))?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$/';
    if (!preg_match($Regular, $cellPhone)) {
        return '手机号码错误';
    }
    $data = [
        'Phone' => $cellPhone,           # 手机号码
        'TemplateId' => md5($templateId), # 模板Id
        'Code' => $codeVal               # 验证码
    ];
    $results = http_curl($requestUrl, 'post', 'json', $data);
    $dataArray = [
        'sms_phone' => $cellPhone,       #	手机号码
        'sms_code' => $codeVal,          #	验证码
        'sms_create_time' => time(),     #	创建时间
    ];
    $counts = Db::name($tName)->where(['sms_phone' => $cellPhone])->whereTime('sms_create_time', '-1 hours')->count();
    if ($counts > 3) {
        return 'NO';
    }
    switch ($results['statusCode']) {
            # 发送成功
        case 200:
            $dataArray['sms_send_status'] = 200;
            $dataArray['sms_send_msg'] = $results['message'];
            $dataArray['sms_content'] = empty($results['data']) ? '' : $results['data'];
            Db::name($tName)->insert($dataArray);
            $codeInfo = 'OK';
            break;
            # 发送失败
        case 300:
            $dataArray['sms_send_status'] = 300;
            $dataArray['sms_send_msg'] = $results['message'];
            $dataArray['sms_content'] = empty($results['data']) ? '' : $results['data'];
            Db::name($tName)->insert($dataArray);
            $codeInfo = 'Failed';
            break;
            # 其它错误
        default:
            $dataArray['sms_send_status'] = $results['statusCode'];
            $dataArray['sms_send_msg'] = $results['message'];
            $dataArray['sms_content'] = $results['data'];
            Db::name($tName)->insert($dataArray);
            $codeInfo = 'Failed';
    }
    return $codeInfo;
}

/**
 * base64数据生成图片
 */
function base64Image($base_image, $name)
{
    //接收base64数据
    $image = $base_image;
    //设置图片名称
    $imageName = date("YmdHis", time()) . '.png';
    //判断是否有逗号 如果有就截取后半部分
    if (strstr($image, ",")) {
        $image = explode(',', $image);
        $image = $image[1];
    }
    //设置图片保存路径
    $path = "uploads/contract";

    //判断目录是否存在 不存在就创建
    if (!is_dir("./" . $path)) {
        mkdir("./" . $path, 0777, true);
    }

    //图片路径
    $imageSrc = $path . "/" . $name . "_" . $imageName;

    //生成文件夹和图片
    $r = file_put_contents("./" . $imageSrc, base64_decode($image));
    if (!$r) {
        return ["code" => 1, "msg" => "图片生成失败！"];
    } else {
        return ["code" => 0, "msg" => "图片生成成功！", "data" => $imageSrc];
    }
}

/**
 * 获取签名内容
 */
function getImgContent($base64)
{
    $return = ["code" => 1, "msg" => "error"];
    if (empty($base64)) {
        $return["msg"] = "没有图片信息！";
    } else {
        $juhe = config('juhe');
        // 接口地址
        $url = $juhe["app_url"];
        // 接口KEY
        $key = $juhe["app_key"];
        // 接口参数
        $data = [
            "key" => $key,
            "ImageBase64" => $base64
        ];
        $results = http_curl($url, 'post', 'json', $data);
        if ($results["error_code"] == 0 && $results["reason"] == 'success') {
            $return["code"] = 0;
            $return["msg"] = $results["reason"];
            $return["data"] = $results["result"]["wenbenxinxi"][0]["wenbenhangneirong"];
        } else {
            $return["msg"] = "签名验证失败！";
        }
    }
    return $return;
}

/**
 * 银行卡验证
 */
function bankCardVerifi($data)
{
    $return = ["code" => 30000, "msg" => "验证接口错误"];
    if (!empty($data)) {
        $bankcard = config("bankcard");
        $arr = [
            'acct_name' => $data['name'],               // 持卡人名称
            'cert_id' => strtoupper($data['idcards']),  // 身份证号
            'acct_pan' => $data['bank_card_number'],    // 银行卡号
            'phone_num' => $data["phone"]               // 手机号
        ];
        $host = $bankcard["host"];
        $path = $bankcard["path"];
        $appcode = $bankcard["appcode"];
        $headers = [];
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $url = $host . $path . "?" . http_build_query($arr);
        $results = http_curl($url, 'get', 'json', '', $headers);
        // file_put_contents("./bankCardVerifi.log", json_encode($results));
        if ($results["resp"]["code"] == 0 && $results["resp"]["desc"] == 'OK') {
            $return = ["code" => 20000, "msg" => "验证接口成功", "data" => $results["data"]];
        } else {
            $return["msg"] = $results["resp"]["desc"];
        }
    }
    return $return;
}

/**
 * curl 请求方法
 * @param $url                   请求地址
 * @param string $type 请求类型
 * @param string $dataType 数据类型
 * @param string $arr 请求数据
 * @param false $header header
 * @param int $timeout 超时时间
 * @param int $connecttimeout
 * @return mixed|string
 */
function http_curl($url, $type = "get", $dataType = "json", $arr = "", $header = false, $timeout = 120, $connecttimeout = 0)
{
    //===1.初始化curl
    $ch = curl_init();
    //===2.设置curl的参数
    curl_setopt($ch, CURLOPT_URL, $url); //发送的路径
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回原生的（Raw）输出
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //禁用后cURL将终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //禁用后cURL将终止从服务端进行验证
    //curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
    if (strtolower($type) == "post") { //post传输数据
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
    }
    if ($header === false) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, []); //启用时会将头文件的信息作为数据流输出
    } else {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //启用时会将头文件的信息作为数据流输出
    }
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //让cURL自己判断使用哪个版本
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout); //在发起连接前等待的时间，如果设置为0，则无限等待
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //设置cURL允许执行的最长秒数
    //===3.采集
    $output = curl_exec($ch); //发送请求并获取返回值
    // logCreateFile("Curl/logCurl", var_export($output, true), "cUrl方法记录");
    // logCreateFile("Curl/logCurl", var_export($arr, true), "cUrl方法记录");
    //===4.关闭并返回数据
    if (strtolower($dataType) == 'json') {
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        $output = json_decode($output, true);
    }
    curl_close($ch);
    return $output;
}

/**
 * 自定义日志方法
 * @param $strPath
 * @param $logInfo
 * @param $logName
 */
function logCreateFile($strPath, $logInfo, $logName)
{
    if (!empty($strPath) && !empty($logInfo)) {
        $defaultFolder = "Logs/";
        $path = $defaultFolder . $strPath;
        if (!is_dir($path)) {
            @mkdir($path, 0777, true);
        }
        $start = "------------------------日志记录开始时间为：" . date('Y-m-d H:i:s') . "----------------------------------" . PHP_EOL;
        $end = PHP_EOL . "------------------------日志记录结束时间为：" . date('Y-m-d H:i:s') . "----------------------------------" . PHP_EOL . PHP_EOL;
        $fileName = !empty($logName) ? convertEncoding($logName) . date('Ymd') . '.log' : date('Ymd') . '.log';
        $logPath = $path . "/" . $fileName;
        $Text = $start . $logInfo . $end;
        file_put_contents($logPath, $Text, FILE_APPEND);
    }
}

/**
 * 转码神器方法
 * @param $string
 * @return string
 */
function convertEncoding($string)
{
    if (empty($string)) {
        return false;
    }
    //根据系统进行配置
    $encode = stristr(PHP_OS, 'WIN') ? 'GBK' : 'UTF-8';
    $string = mb_convert_encoding($string, $encode, 'UTF-8');
    return $string;
}

/**
 * 截取两位小数，不四舍五入
 */
function strTwoBits($str)
{
    return sprintf("%.2f", substr(sprintf("%.3f", $str), 0, -2));
}

/**
 * 计算环比
 */
function calculateHb($currentPeriod, $priorPeriod)
{
    $hb_type = 2;
    $hb_num = 0;
    if ($currentPeriod * 100 > $priorPeriod * 100) {
        $hb_type = 1;
    }
    if ($priorPeriod > 0 && $currentPeriod > 0) {
        $hb = $currentPeriod * 100 - $priorPeriod * 100;
        $hb_num = bcdiv(abs($hb), ($priorPeriod * 100), 2) * 100;
    } else {
        if ($priorPeriod == 0 && $currentPeriod == 0) {
            $hb_num = 0;
        } else {
            $hb_num = 100;
        }
    }
    return ['hb_type' => $hb_type, 'hb_num' => $hb_num];
}

/*
 * 处理图片
 */
function processImage($field, $images)
{
    for ($i = 0; $i < count($images); $i++) {
        if (!empty($images[$i][$field])) {
            $images[$i][$field] = config("app_url") . $images[$i][$field];
        } else {
            $images[$i][$field] = "/static/Admin/img/default.png";
        }
    }
    return $images;
}

/**
 * 二位数组排序
 */
function arraySort($arr, $keys, $type = 'asc') {
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v){
        $keysvalue[$k] = $v[$keys];
    }
    $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
       $new_array[$k] = $arr[$k];
    }
    return $new_array;
}